<?php
namespace App\Http\Controllers\Member;


use App\Models\Employ;
use Illuminate\Http\Request;
use App\Models\EmployExt;
use Illuminate\Support\Facades\DB;
use App\Models\Tags;
use App\Models\TagsNews;
use App\Models\Category;
use Illuminate\Support\Facades\Input;
use App\Models\SystemSetting;
use Illuminate\Support\Facades\Log;
/**
 *
 * @author Joker
 *        
 */
class EmployController extends MemberController
{
    protected $catgory;
    
    public function __construct()
    {
        parent::__construct();
        $this->catgory = Category::where(array('app'=>'employ','pid'=>0))->get();
    }
    
    public function index(){

        $sort = Input::get('sort',0);
        $query = Employ::where('user_id','=',$this->uid)->with('exts');

        switch ($sort){
            case 1:  //浏览量
                $query->join('employ_ext as eext', 'eext.news_id', '=', 'employ.id')
                      ->orderBy("eext.reading_num",'desc');
                break;
            case 2:  //评论数
                $query->join('employ_ext as eext', 'eext.news_id', '=', 'employ.id')
                      ->orderBy('eext.comment_num','desc');
                break;
            default:
                $query->orderBy('created_at','desc');
        }

        $employ = $query->with('category')->with('attachment')->orderBy('updated_at','desc')->paginate(10);
//        $employ = Employ::with('exts')->with('category')->with('attachment')->where('user_id','=',$this->uid)->orderBy('created_at','desc')->paginate(10);

        return view('member.employ.document')
            ->with('documents',$employ)->with('sort',$sort);
    }
    
    /**
     * 编辑
     * 文档
     */
    public function show($id)
    {
        $employ = Employ::with('exts')->where(array('user_id'=>$this->uid,'id'=>$id))->first();
        if(empty($employ))
            abort(404);
        
        $array =array('dest_dir'=>'employ','attachment'=>true,'_token'=>csrf_token());
        $options =  str_replace('"','\'',json_encode($array));
        $opts = base64_encode(serialize($array));
        
        $newsTag = array();
        foreach ($employ->tags as $tag)
        {
            $tags = Tags::where('tags_id','=',$tag->tags_id)->first();
            if($tags)
                $newsTag[] = $tags->tags_name;
        }
        $cateGory = $this->getCate($employ->cat_id, $employ->category->pid,"employ");
        return view('member.employ.create')
                ->with('nav',1)
                ->with('options',$options)
                ->with('item',$this->item)
                ->with('newstag',implode(",", $newsTag))
                ->with('categorys',$cateGory)
                ->with('opts',$opts)
                ->with('result',$employ)
                ->with('type',$this->catgory);
    }
    
    /**
     * 投稿
     */
    public function create()
    {
        $array =array('dest_dir'=>'employ','attachment'=>true,'_token'=>csrf_token());
        $options =  str_replace('"','\'',json_encode($array));
        $opts = base64_encode(serialize($array));
        return view('member.employ.create')
                ->with('nav',1)
                ->with('options',$options)
                ->with('opts',$opts)
                ->with('type',$this->catgory);
    }
    
    /**
     * 保存数据
     */
    public function store(Request $req)
    {
        $this->validate($req, [
            'title'         => 'required|max:255',
            'content'       => 'required',
            'thumb'         => 'required',
        ]);
        
        $data = $req->only(
            array(
                'title','type','child_1','child_2','child_3','thumb','description','tagsinput',
                'content','from','user_id','author','price','newsid'
            )
        );
        if(empty($data['description']) || mb_strlen($data['description'])<10 )
            return $this->formatJson('error','文章简介不可为空,且不小于10个中文字符');
        
        $data['cat_id'] = $this->getTypes($data['type'],$data['child_1'],$data['child_2'],$data['child_3']);
        if(empty($data['cat_id']))
            return $this->formatJson('error','请选择分类！');
        //敏感词过滤
        $sysword = SystemSetting::where('varname','=','sensitive_words')->first();
        $wordstr = unserialize($sysword['value']);

        $attributes = array(
            'title'         =>      filter_words($data['title'], $wordstr),
            'cat_id'        =>      $data['cat_id'],
            'thumb'         =>      $data['thumb'],
            'description'   =>      filter_words($data['description'], $wordstr),
            'content'       =>      filter_words($data['content'], $wordstr),
            'from'          =>      filter_words($data['from'], $wordstr),
            'author'        =>      filter_words($data['author'], $wordstr),
            'status'        =>      1,
            'user_id'       =>      $this->uid
        );
        //保存tags
        $tagids = array();
        $tags = strToArray($data['tagsinput'], ",");
        
        if(isset($data['newsid']) && is_numeric($data['newsid']) && $data['newsid'] > 0)
        {
            $news = Employ::find($data['newsid']);
            foreach ($attributes as $key=>$val)
            {
                $news->$key = $val;
            }
            DB::beginTransaction();
            try {
                $news->save();
                foreach ($tags as $tg){
                    if(!empty(trim($tg)))
                    {
                        $tagsModel = Tags::firstOrCreate(['tags_name'=>trim($tg)]);
                        $tagids[] = $tagsModel->tags_id;
                    }
                }
                //建立关联 文章与标签
                TagsNews::where('news_id','=',$news->id)->delete();
                foreach ($tagids as $tgd){
                    TagsNews::firstOrCreate(['tags_id'=>$tgd,'news_id'=>$news->id]);
                }
                $this->employextinfo($news, $data);
                DB::commit();
            }catch (\PDOException $e){
                Log::info(['编辑就业指南文章异常'=>$e->getMessage()]);
                DB::rollBack();
                return $this->formatJson('error','数据异常！');
            }
        }
        else
        {
            $attributes['is_validate'] = 0;
            DB::beginTransaction();
            try {
                $news = Employ::firstOrCreate($attributes);
                foreach ($tags as $tg){
                    if(!empty(trim($tg)))
                    {
                        $tagsModel = Tags::firstOrCreate(['tags_name'=>trim($tg)]);
                        $tagids[] = $tagsModel->tags_id;
                    }
                }
                //建立关联 文章与标签
                TagsNews::where('news_id','=',$news->id)->delete();
                foreach ($tagids as $tgd){
                    TagsNews::firstOrCreate(['tags_id'=>$tgd,'news_id'=>$news->id]);
                }
                $this->employextinfo($news, $data);
                DB::commit();
            }catch (\PDOException $e){
                Log::info(['新建就业指南文章异常'=>$e->getMessage()]);
                DB::rollBack();
                return $this->formatJson('error','数据异常！');
            }
        }
        return $this->formatJson('success','文章保存成功',$news,'/member/index');
    }
    
    /**
     * 删除
     * @param integer $id
     */
    public function destroy($id) {
        $employ = Employ::where(array('user_id'=>$this->uid,'id'=>$id))->first();
        if(empty($employ))
        {
            return  $this->formatJson('falied','抱歉，您要删除的文章不存在!');
        }
        else 
        {   
            DB::transaction(function() use ($employ){
                $employ->forceDelete();
                EmployExt::where('news_id','=',$employ->id)->delete();
            });
            return $this->formatJson('success','文章：［'.$employ->title.'］ 删除成功');
        }
    }
    
    /**
     * 扩展信息
     */
    private function employextinfo($news,$data)
    {
        $employExt = EmployExt::find($news->id);
        if(empty($employExt))
        {
            $employExt = new EmployExt();
            $employExt->news_id = $news->id;
        }
        $employExt->price = $data['price'];
        $employExt->template_id = 'default';
        $employExt->save();
    }
}